﻿using Cassandra;
using dreamwork.core.Infrastructure.Data.Cassandra;
using dreamwork.exam.api.Data;
using dreamwork.exam.api.Infrastructure.Cassandra;
using Dreamwork.Core.Infrastructure;
using DreamWork.Web.API.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Net;

namespace dreamwork.exam.api
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			var hostAddress = $"{Configuration["Schema"]}://{Configuration["DREAMWORK_DNS_NAME_OR_IP"]}";
			services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

			services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
			  .AddIdentityServerAuthentication(options =>
			  {
				  options.Authority = $"{hostAddress}:5200";
				  options.RequireHttpsMetadata = false;

				  options.ApiName = "dreamwork.exam.api";
			  });

			services.AddSingleton<ICluster>(Cluster.Builder()
					.AddContactPoint(
						new IPEndPoint(IPAddress.Parse(Configuration.GetValue<string>("Cassandra:IPAddress")),
						Configuration.GetValue<int>("Cassandra:Port")))
					.Build());

			services.AddTransient<ICanssandraRepository<ExamUser>, ExamRepository>();

			#region Swagger
			services.AddSwaggerGen(options =>
			{
				options.DescribeAllEnumsAsStrings();
				options.SwaggerDoc("v1", new Info { Title = "Dreamwork Exam API", Version = "v1" });
				options.OperationFilter<HttpAuthHeaderFilter>();
			});
			#endregion

			#region Cors
			services.AddCors(options =>
			{
				options.AddPolicy("CorsPolicy",
					builder => builder.AllowAnyOrigin()
					.AllowAnyMethod()
					.AllowAnyHeader()
					.AllowCredentials());
			});
			#endregion
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
		{
			//loggerFactory.AddConsole(Configuration.GetSection("Logging"));
			//loggerFactory.AddDebug();
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseHsts();
			}
			app.UseMvc();
			app.UseCors("CorsPolicy");
			app.UseSwagger();
			app.UseAuthentication();
			app.UseHttpsRedirection();
			app.UseMvcWithDefaultRoute();
			app.UseStaticFiles();
			app.UseSwagger()
			   .UseSwaggerUI(c =>
			   {
				   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dreamwork.Exam.API");
			   });
		}
	}
}
